package com.common.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtils {

    //常量
    public static final long EXPIRE = 10000000L * 60 * 60 ; //token过期时间
    public static final SecureDigestAlgorithm<SecretKey,SecretKey> APP_SECRET = Jwts.SIG.HS256; //秘钥
    public static final String APP_KEY = "s3cR3tK3yF0rJWTs1gn1ngAndV3r1f1c4t10n";

    //生成token字符串的方法
    public static String getJwtToken(Long id){
        Date date = new Date();

        return Jwts.builder()
                .header()
                .add("typ","JWT")
                .add("alg","HS256")
                .and().claim("userId",id)
                .expiration(new Date(date.getTime()+EXPIRE))
                .issuedAt(date)
                .signWith(Keys.hmacShaKeyFor(APP_KEY.getBytes()),APP_SECRET)
                .compact();
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            SecretKey secretKey = Keys.hmacShaKeyFor(APP_KEY.getBytes());
            JwtParser parser = Jwts.parser().verifyWith(secretKey).build();
            Jws<Claims> jws = parser.parseSignedClaims(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(ObjectUtils.isEmpty(jwtToken)) return false;
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public static Long getUserId(String jwtToken) {
        if (ObjectUtils.isEmpty(jwtToken)) return null;
        Jws<Claims> claimsJws = Jwts.parser().
                verifyWith(Keys.hmacShaKeyFor(APP_KEY.getBytes())).build().parseSignedClaims(jwtToken) ;
        Claims claims = claimsJws.getBody();
        return Long.valueOf(claims.get("userId").toString());
    }
}
